<!-- 广告投放统计 -->
<template>
  <div class="ad-impressions-page">

    <!-- 搜索过滤区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="广告创意">
          <el-input
              v-model="filterForm.creativeTitle"
              placeholder="输入创意标题"
              clearable
              @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容标题">

          <el-input
              v-model="filterForm.contentTitle"
              placeholder="输入内容标题"
              clearable
              @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item label="展示位置">
          <el-select
              v-model="filterForm.positionCode"
              placeholder="选择展示位置"
              clearable
              style="width: 180px"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="文章页顶部" :value="1"></el-option>
            <el-option label="文章页底部" :value="2"></el-option>
            <el-option label="信息流" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <i class="el-icon-search"></i> 搜索
          </el-button>
          <el-button @click="resetFilter">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 展示记录列表 -->
    <el-card class="impressions-card">
      <div slot="header" class="clearfix">
        <span>广告展示记录列表</span>
        <el-button style="float: right; margin-top: -5px" type="danger" @click="deleteSelect">
          <i class="el-icon-plus"></i> 批量删除
        </el-button>
      </div>

      <el-table
          :data="impressionsList"
          border
          fit
          style="width: 100%"
          @selection-change="handleSelectionChange"

      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="impressionId" label="展示ID" ></el-table-column>
        <el-table-column prop="creativeTitle" label="广告创意">
          <template #default="{ row }">
            <el-tooltip :content="row.creativeTitle" placement="top">
              <span>{{ row.creativeTitle }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
<!--        <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>-->
        <el-table-column prop="username" label="用户名称" ></el-table-column>
        <el-table-column prop="contentTitle" label="内容标题">
          <template #default="{ row }">
            <el-tooltip :content="row.contentTitle" placement="top">
              <span>{{ row.contentTitle }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="positionCode" label="展示位置">
          <template #default="{ row }">
            {{ getPositionText(row.positionCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="impressionTime" label="展示时间" >
          <template #default="{ row }">
            {{ formatDate(row.impressionTime) }}
          </template>
        </el-table-column>
        <el-table-column label="设备信息" >
          <template #default="{ row }">
            <div v-if="row.deviceInfo">
              <div>系统: {{ row.deviceInfo.os || '未知' }}</div>
              <div>浏览器: {{ row.deviceInfo.browser || '未知' }}</div>
              <div>设备: {{ row.deviceInfo.device_type || '未知' }}</div>
            </div>
            <div v-else>未知设备信息</div>
          </template>
        </el-table-column>
        <el-table-column label="地理位置" >
          <template #default="{ row }">
            <div v-if="row.location">
              <div>城市: {{ row.location.city || '未知' }}</div>
              <div>地区: {{ row.location.region || '未知' }}</div>
              <div>国家: {{ row.location.country || '未知' }}</div>
            </div>
            <div v-else>未知地理位置</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="{ row }">
            <el-link type="primary" @click="viewDetails(row)">详情</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 详情模态框 -->
    <el-dialog
        title="展示记录详情"
        v-model="detailDialogVisible"
        width="80%"
        :before-close="handleDetailClose"
        :close-on-click-modal="false"
    >
      <div class="detail-content">
        <div  element-loading-text="数据加载中..." element-loading-spinner="el-icon-loading">
          <el-row :gutter="20">
            <!-- 基础信息卡片 -->
            <el-col :span="24">
              <el-card class="detail-card">
                <div class="card-title">基础信息</div>
                <el-row :gutter="15">
                  <el-col :sm="24" :md="8">
                    <el-descriptions title="展示基本信息" :column="1">
                      <el-descriptions-item label="展示ID">{{ detailForm.impressionId }}</el-descriptions-item>
                      <el-descriptions-item label="广告创意">{{ detailForm.creativeTitle }}</el-descriptions-item>
                      <el-descriptions-item label="用户ID">{{ detailForm.userId }}</el-descriptions-item>
                      <el-descriptions-item label="用户名称">{{ detailForm.username || '未获取到用户信息' }}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                  <el-col :sm="24" :md="8">
                    <el-descriptions title="内容信息" :column="1">
                      <el-descriptions-item label="内容ID">{{ detailForm.contentId }}</el-descriptions-item>
                      <el-descriptions-item label="内容标题">{{ detailForm.contentTitle || '未获取到内容标题' }}</el-descriptions-item>
                      <el-descriptions-item label="展示位置">{{ getPositionText(detailForm.positionCode) || '未知位置' }}</el-descriptions-item>
                      <el-descriptions-item label="展示时间">{{ detailForm.impressionTime || '未记录时间' }}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                  <el-col :sm="24" :md="8">
                    <el-descriptions title="技术信息" :column="1">
                      <el-descriptions-item label="IP地址">{{ detailForm.ipAddress || '未记录IP' }}</el-descriptions-item>
                      <el-descriptions-item label="设备信息">{{ detailForm.deviceInfo.os || '未知设备信息' }}</el-descriptions-item>
                      <el-descriptions-item label="地理位置">{{ detailForm.location.city || '未知地理位置' }}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>

            <!-- 设备信息卡片 -->
            <el-col :span="24">
              <el-card class="detail-card">
                <div class="card-title">设备与环境信息</div>
                <el-row :gutter="15">
                  <el-col :sm="24" :md="12">
                    <el-card class="info-card">
                      <div class="card-subtitle">设备信息</div>
                      <div v-if="detailForm.deviceInfo && Object.keys(detailForm.deviceInfo).length > 0">
                        <div class="info-item">
                          <span class="info-label">操作系统：</span>
                          <span class="info-value">{{ detailForm.deviceInfo.os || '未知' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">浏览器：</span>
                          <span class="info-value">{{ detailForm.deviceInfo.browser || '未知' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">设备类型：</span>
                          <span class="info-value">{{ detailForm.deviceInfo.device_type || '未知' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">设备型号：</span>
                          <span class="info-value">{{ detailForm.deviceInfo.model || '未知' }}</span>
                        </div>
                      </div>
                      <div v-else>
                        <div class="empty-info">未获取到设备信息</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :sm="24" :md="12">
                    <el-card class="info-card">
                      <div class="card-subtitle">地理位置信息</div>
                      <div v-if="detailForm.location && Object.keys(detailForm.location).length > 0">
                        <div class="info-item">
                          <span class="info-label">国家/地区：</span>
                          <span class="info-value">{{ detailForm.location.country || '未知' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">省份/州：</span>
                          <span class="info-value">{{ detailForm.location.region || '未知' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">城市：</span>
                          <span class="info-value">{{ detailForm.location.city || '未知' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">运营商：</span>
                          <span class="info-value">{{ detailForm.location.isp || '未知' }}</span>
                        </div>
                      </div>
                      <div v-else>
                        <div class="empty-info">未获取到地理位置信息</div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>

            <!-- 关联信息卡片 -->
            <el-col :span="24">
              <el-card class="detail-card">
                <div class="card-title">关联广告与内容信息</div>
                <el-row :gutter="15">
                  <el-col :sm="24" :md="12">
                    <el-card class="info-card">
                      <div class="card-subtitle">广告创意信息</div>
                      <div v-if="detailForm.creativeId">
                        <div class="info-item">
                          <span class="info-label">创意ID：</span>
                          <span class="info-value">{{ detailForm.creativeId }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">创意标题：</span>
                          <span class="info-value">{{ detailForm.creativeTitle || '未获取到创意标题' }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">广告类型：</span>
                          <span class="info-value">{{ detailForm.adType || '未知类型' }}</span>
                        </div>
                        <div class="info-actions">
                          <el-button size="mini" type="primary" @click="viewCreativeDetail">查看创意详情</el-button>
                        </div>
                      </div>
                      <div v-else>
                        <div class="empty-info">未关联广告创意</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :sm="24" :md="12">
                    <el-card class="info-card">
                      <div class="card-subtitle">展示内容信息</div>
                      <div v-if="detailForm.contentId">
                        <div class="info-item">
                          <span class="info-label">内容ID：</span>
                          <span class="info-value">{{ detailForm.contentId }}</span>
                        </div>
                        <div class="info-item">
                          <span class="info-label">内容标题：</span>
                          <span class="info-value">{{ detailForm.contentTitle || '未获取到内容标题' }}</span>
                        </div>
                        <div class="info-actions">
                          <el-button size="mini" type="primary" @click="viewContentDetail">查看内容详情</el-button>
                        </div>
                      </div>
                      <div v-else>
                        <div class="empty-info">未关联展示内容</div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from '@/utils/request';
import dayjs from 'dayjs';

export default {
  name: 'AdImpressionsPage',
  data() {
    return {
      filterForm: {
        creativeTitle: '',
        contentTitle: '',
        positionCode: '',
      },
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      exportLoading: false,
      impressionsList: [],
      detailDialogVisible: false,
      detailForm: {
        impressionId: '',
        creativeId: '',
        creativeTitle: '',
        adType: '',
        userId: '',
        username: '',
        contentId: '',
        contentTitle: '',
        positionCode: '',
        positionText: '',
        impressionTime: '',
        ipAddress: '',
        deviceInfo: {},
        deviceInfoText: '',
        location: {},
        locationText: ''
      },
      // 位置编码映射
      positionMap: {
        1: '文章页顶部',
        2: '文章页底部',
        3: '信息流'
      },
      // 统计数据
      totalImpressions: 0,
      todayImpressions: 0,
      hotPosition: '暂无数据',
      hotCreative: '暂无数据'
    };
  },
  mounted() {
    this.fetchImpressionsList();
  },
  methods: {
    // 获取展示记录列表
    async fetchImpressionsList() {
      this.loading = true;
      try {
        const params = this.buildQueryParams();
        const response = await axios.get('/adImpression/page', { params });

        if (response.data.code === 200) {
          this.impressionsList = response.data.data.records.map(item => {
            // 格式化设备信息和地理位置
            item.deviceInfo = item.deviceInfo ? JSON.parse(item.deviceInfo) : {};
            item.location = item.location ? JSON.parse(item.location) : {};
            return item;
          });
          this.total = response.data.data.total;
        } else {
          this.$message.error(response.data.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取广告展示记录失败', error);
        this.$message.error('网络错误，获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    // 构建查询参数
    buildQueryParams() {
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        creativeTitle: this.filterForm.creativeTitle,
        contentTitle: this.filterForm.contentTitle,
        positionCode: this.filterForm.positionCode
      };

      return params;
    },

    // 处理搜索
    handleFilter() {
      this.currentPage = 1;
      this.fetchImpressionsList();
    },

    // 重置搜索条件
    resetFilter() {
      this.filterForm = {
        creativeTitle: '',
        contentTitle: '',
        positionCode: '',
      };
      this.currentPage = 1;
      this.fetchImpressionsList();
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchImpressionsList();
    },

    // 处理当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchImpressionsList();
    },

    // 获取位置文本
    getPositionText(code) {
      return this.positionMap[code] || '未知位置';
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },

    // 查看创意详情
    viewCreativeDetail() {
      if (this.detailForm.creativeId) {
        this.$message({
          type: 'info',
          message: `即将查看创意ID: ${this.detailForm.creativeId} 的详情`
        });
        // 实际项目中应跳转到创意详情页面
        // this.$router.push(`/ad-creatives/${this.detailForm.creativeId}`);
      } else {
        this.$message.warning('暂无创意ID，无法查看详情');
      }
    },

    // 查看内容详情
    viewContentDetail() {
      if (this.detailForm.contentId) {
        this.$message({
          type: 'info',
          message: `即将查看内容ID: ${this.detailForm.contentId} 的详情`
        });
        // 实际项目中应跳转到内容详情页面
        // this.$router.push(`/contents/${this.detailForm.contentId}`);
      } else {
        this.$message.warning('暂无内容ID，无法查看详情');
      }
    },

    // 查看详情
    viewDetails(row) {
      this.detailForm = {...row};
      console.log(row)
      this.detailDialogVisible = true;
    },


    // 关闭详情模态框
    handleDetailClose(done) {
      this.detailDialogVisible = false;
      done();
    },

    // 批量删除
    deleteSelect(){
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录');
        return;
      }

      const impressionIds = this.multipleSelection.map(item => item.impressionId);

      this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 条记录吗？`, '批量删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端批量删除接口
        axios.post('/adImpression/deleteSelect', impressionIds).then(response => {
          if (response.data.code === 200) {
            this.$message.success(`成功删除 ${this.multipleSelection.length} 条记录`);
            this.multipleSelection = [];
            this.fetchImpressionsList();
          } else {
            this.$message.error(response.data.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败: ' + (error.response?.data?.message || error.message));
        })
      }).catch(() => {
        this.$message.info('删除操作已取消');
      });
    },
    // 根据id删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/adImpression/delete',{
          params:{
            impressionId: row.impressionId
          }
        }).then( () =>{
          const index = this.impressionsList.findIndex(item => item.impressionId === row.impressionId)
          if (index !== -1) {
            this.impressionsList.splice(index, 1)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }

  }
};
</script>

<style scoped>
.ad-impressions-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  padding: 10px 0;
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  height: 100%;
}

.statistics-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.impressions-card {
  margin-bottom: 20px;
}

.tools {
  float: right;
}

.detail-content {
  padding: 20px 0;
}
.detail-content {
  padding: 10px 0;
}

.detail-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.card-subtitle {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.info-card {
  height: 100%;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
}

.last-child {
   border-bottom: none;
   margin-bottom: 0;
   padding-bottom: 0;
 }


.info-label {
  min-width: 80px;
  color: #606266;
  font-weight: normal;
}

.info-value {
  flex: 1;
  color: #303133;
}

.info-actions {
  margin-top: 15px;
}

.empty-info {
  color: #909399;
  padding: 15px 0;
  text-align: center;
}
</style>
